package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class RefuelCardRegController {
	//导入activiti工具
	ActitiviUtil activitiUtil = new ActitiviUtil();
	// 自动注入
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private CustomLogService customLogService;
	@Autowired
	private RefuelCardRegService refuelCardRegService;
	@Autowired
	private RefuelCardRegEntryService refuelCardRegEntryService;
	@Autowired
	private CarService carService;
	@Autowired
	private  OilspecService oilspecService;
	@Autowired
	private TeamService teamService;
	@Autowired
	private CoaceGroupController coaceGroupController;
	//自动注入
	@Autowired
	private FillingCardService fillingCardService;
	@Autowired
	private PersonService personService;
	//自定义流程工具
	private Axamine axamine = new Axamine();
	
	/**
	 * 查询加油卡加油登记
	 * @param request
	 * @param fnumber
	 * @param fdescription
	 * @param beginTime
	 * @param endTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/queryRefuelCardReg/look.action")
	public String selRefuelCardReg(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "fdescription", defaultValue = "") String fdescription
            , @RequestParam(value = "carName", defaultValue = "") String carName 
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "")String endTime
			, @RequestParam(value = "type",defaultValue = "") String type
			, @RequestParam(value = "selectState",required = false,defaultValue = "-1") String selectState)throws Exception{
		PageBean<RefuelCardReg> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格
            fdescription = fdescription.trim();
            carName = carName.trim();
            beginTime=beginTime.trim();
            endTime=endTime.trim();
			if("1".equals(selectState)){//如果传过来的标记为1 所以业务日期为空默认查询全部
				pb=getPageBean(request,user.getFcompanyid(),fnumber,fdescription,carName,null,null);
			}else{
				//默认时间
				if ("".equals(beginTime) && "".equals(endTime)) {
					beginTime = TimeFormat.getMonth();
					endTime = TimeFormat.getNowTime();
				}
				//获取分页
				pb=getPageBean(request,user.getFcompanyid(),fnumber,fdescription,carName,beginTime,endTime);
			}
            //把获取到的数据传回页面
            if(carName.equals("")){
            	carName=null;
            }

            //计数器
            int i = 0;
            //缓存需要删除的序列
            List<Integer> tem = new ArrayList<>();
            //获取当前分页的值
            List<RefuelCardReg> refuelCardRegList = pb.getBeanList();          
           
            for (RefuelCardReg refuelCardReg : refuelCardRegList) {
                //查询车辆信息
            	refuelCardReg.setRefuelCardRegEntryList(refuelCardRegEntryService.selectAll(refuelCardReg.getFid()));
                i++;
                //如果子类为空则记住该序列序号
                if (refuelCardReg.getRefuelCardRegEntryList().size() == 0) {
                    tem.add(i);
                }
            }

            //进行集合删除
            for (int j = 0; j < tem.size(); j++) {
            	refuelCardRegList.remove(tem.get(j) - j - 1);
            }
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("fdescription", fdescription);
            request.setAttribute("carName", carName);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);
            request.setAttribute("refuelCardRegList", refuelCardRegList);
            request.setAttribute("pb", pb);
			request.setAttribute("flag", type);
			request.setAttribute("selectState",selectState);
		} catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
		return "backHome/carManagement/refuelCardReg/refuelCardRegList";
	}
	
	/**
	 * 跳转到加油卡加油登记页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoAddRefuelCardReg")
	public String intoAddRefuelCardReg(HttpServletRequest request,String type)throws Exception{
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取最大编号
        /*String number = refuelCardRegService.selectFnumber(user.getFcompanyid());*/
		//根据上一个编码获取编码
        String fnumber = GetFnumber.fnumbers("JYDJ");
		//获取模式框里面数据
		//获取车辆
        List<Car> cars = carService.queryCar(user.getFcompanyid());
        //获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//业务时间
		String time = sdf.format(new Date());
		//获取其汽油规格
		List<Oilspec> oilspecs = oilspecService.queryOilsperAll();
		//获取职员
		//拼接SQL语句
		StringBuffer psql = new StringBuffer();
		psql.append("select T.FID, T.FNUMBER,to_char(t.CFBIRTHDAY,'YYYY-MM-DD ') cfbirthdays,to_char(t.cfstartdate,'YYYY-MM-DD ') cfstartdate,");
		psql.append("to_char(t.cfenddate,'YYYY-MM-DD ') cfenddate,to_char(t.cfbegindate,'YYYY-MM-DD ') cfbegindate,to_char(t.CFHTDQSJ,'YYYY-MM-DD ') cfhtdqsj,");
		psql.append("T.CFIDCARDNO, T.CFCELL, T.CFADDRESS,T.CFPERSONTYPE, T.CFSEX,T.CFXCTZ, T.CFGWYD, T.CFQJJL, T.CFWJJLJL,p.fname_l2 as positiongradeName,t.cfaccountsno, ");
		psql.append("T.CFSHJLJL,T.FNAME_L2,T.CFZSTC,T.CFPXTC,A.FNAME_L2 AS CFPERSONDEPNAME,C.fnumber AS CFCARNAME from ct_ds_person t left join ");
		psql.append("CT_DS_ADMIN A ON A.FID=T.CFPERSONDEPID left join CT_DS_CAR C ON C.FID=T.CFCARID left join CT_DS_POSITIONGRADE p on t.cfjobgradeid=p.fid ");
		List<Person> persons = personService.selectPerson(psql.toString());
		// 获取教练组
		// 查询教练组信息
		Map map2 = coaceGroupController.getPageCoaceGroup(request, "", "", "0");
		// 获取教练队
		List<Team> teams = teamService.queryTeamByFcontrolunitid(user.getFcompanyid());
		//获取需要查找或者修改的驾校车辆加油登记信息
		//根据公司id和名称查询
		List<FillingCard> fillingCardList = fillingCardService.selectFillingCardByfnameL2(user.getFcompanyid(), null);	   				
		request.setAttribute("fillingCardList", fillingCardList);
		request.setAttribute("department", department);
		request.setAttribute("user", user);
		request.setAttribute("fnumber", fnumber);
		request.setAttribute("cars", cars);
		request.setAttribute("time", time);
		request.setAttribute("type",type);
		request.setAttribute("oilspecs",oilspecs);
		request.setAttribute("persons",persons);
		request.setAttribute("coacegroups", map2.get("sList"));
		request.setAttribute("teams", teams);
		return "backHome/carManagement/refuelCardReg/addRefuelCardReg";
	}
	
	/**
	 * 增加加油卡加油登记
	 * @param request
	 * @param refuelCardReg
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/addRefuelCardReg")
	public String addRefuelCardReg(HttpServletRequest request,RefuelCardReg refuelCardReg)throws Exception{
		String [] fseq = request.getParameterValues("fseq");//序号
		String [] carId =request.getParameterValues("carId");//车辆Id
		String [] cfqty = request.getParameterValues("cfqty");//数量
		String [] cftrainid=request.getParameterValues("cftrainName");//教练id
		String [] cfkemu=request.getParameterValues("cfkemu");//科目
		String [] cfdepname=request.getParameterValues("cfdepname");//部门名称

		 String[] cfgroupid=request.getParameterValues("cfgroupName");//教练组名称
		 String [] cfteamid=request.getParameterValues("cfteamName");//教练队名称

		 String[] cfoilspecid=request.getParameterValues("cfoilspecName");//汽油规格id

		 String[] cfcartype=request.getParameterValues("cfcartype");//车型
		for (int i=0;i<cfqty.length;i++){
			if(cfqty[i] == null || "".equals(cfqty[i])){
				cfqty[i] ="0";
			}
		}
		String [] cfprice = request.getParameterValues("cfprice");//单价
		for (int i=0;i<cfprice.length;i++){
			if(cfprice[i] == null || "".equals(cfprice[i])){
				cfprice[i] ="0";
			}
		}
		String [] cfamount = request.getParameterValues("cfamount");//金额
		for (int i=0;i<cfamount.length;i++){
			if(cfamount[i] == null || "".equals(cfamount[i])){
				cfamount[i] ="0";
			}
		}
		String [] cfdesc =request.getParameterValues("cfdesc");//备注

		String []cfbizdate=request.getParameterValues("cfbizdate");//加油时间
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
	    //利用UUID生成fid
	    refuelCardReg.setFid(GetFid.UUIDIntoFid());
	    //公司id
	    refuelCardReg.setCfficompanyid(user.getFcompanyid());
		//控制单元id
	    refuelCardReg.setFcontrolunitid(user.getFcompanyid());
		//创建人id
	    refuelCardReg.setFcreatorid(user.getFid());
	    //获取当前时间
	  	String createTime = TimeFormat.timeFormat(new Date());
	  	String cfrefuelid=request.getParameter("cfrefuelid");
	  	refuelCardReg.setCfrefuelid(cfrefuelid);
	  	refuelCardReg.setFcreatetime(createTime);
		//添加
	  	int row=refuelCardRegService.addRefuelCardReg(refuelCardReg, fseq, carId, cfqty, cfprice, cfamount, cfdesc,cftrainid,cfkemu,cfdepname,cfgroupid,cfteamid,cfoilspecid,cfcartype,cfbizdate);
	  	String result="";
	  	if(row>0){
			result="1";
		}
	  	//添加日志
        customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date()) + "加油卡加油登记进行新增", null, user.getFid());
		return "redirect:/DrivingSys/intoAddRefuelCardReg?type="+result;
	}
	
	/**
	 * 跳转到加油卡加油登记修改页面
	 * @param request
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoUpdateRefuelCardReg")
	public String intoUpdateRefuelCardReg(HttpServletRequest request,String fid)throws Exception{
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取车辆
        List<Car> cars = carService.queryCar(user.getFcompanyid());
        //根据公司id和名称查询
		List<FillingCard> fillingCardList = fillingCardService.selectFillingCardByfnameL2(user.getFcompanyid(), null);
		//根据fid获取加油卡加油登记
		RefuelCardReg refuelCardReg = refuelCardRegService.selRefuelCardRegByFid(fid);
		refuelCardReg.setRefuelCardRegEntryList(refuelCardRegEntryService.selRefuelCardRegEntryByParentId(refuelCardReg.getFid(), null));
		//获取其汽油规格
		List<Oilspec> oilspecs = oilspecService.queryOilsperAll();
		//获取职员
		//拼接SQL语句
		StringBuffer psql = new StringBuffer();
		psql.append("select T.FID, T.FNUMBER,to_char(t.CFBIRTHDAY,'YYYY-MM-DD ') cfbirthdays,to_char(t.cfstartdate,'YYYY-MM-DD ') cfstartdate,");
		psql.append("to_char(t.cfenddate,'YYYY-MM-DD ') cfenddate,to_char(t.cfbegindate,'YYYY-MM-DD ') cfbegindate,to_char(t.CFHTDQSJ,'YYYY-MM-DD ') cfhtdqsj,");
		psql.append("T.CFIDCARDNO, T.CFCELL, T.CFADDRESS,T.CFPERSONTYPE, T.CFSEX,T.CFXCTZ, T.CFGWYD, T.CFQJJL, T.CFWJJLJL,p.fname_l2 as positiongradeName,t.cfaccountsno, ");
		psql.append("T.CFSHJLJL,T.FNAME_L2,T.CFZSTC,T.CFPXTC,A.FNAME_L2 AS CFPERSONDEPNAME,C.fnumber AS CFCARNAME from ct_ds_person t left join ");
		psql.append("CT_DS_ADMIN A ON A.FID=T.CFPERSONDEPID left join CT_DS_CAR C ON C.FID=T.CFCARID left join CT_DS_POSITIONGRADE p on t.cfjobgradeid=p.fid ");
		List<Person> persons = personService.selectPerson(psql.toString());
		// 获取教练组
		// 查询教练组信息
		Map map2 = coaceGroupController.getPageCoaceGroup(request, "", "", "0");
		// 获取教练队
		List<Team> teams = teamService.queryTeamByFcontrolunitid(user.getFcompanyid());
		//获取需要查找或者修改的驾校车辆加油登记信息
		request.setAttribute("fillingCardList", fillingCardList);
		request.setAttribute("department", department);
		request.setAttribute("refuelCardReg", refuelCardReg);
		request.setAttribute("cars", cars);
		request.setAttribute("oilspecs",oilspecs);
		request.setAttribute("persons",persons);
		request.setAttribute("coacegroups", map2.get("sList"));
		request.setAttribute("teams", teams);
		return "backHome/carManagement/refuelCardReg/updateRefuelCardReg";
	}
	
	/**
	 * 修改加油卡加油登记
	 * @param request
	 * @param refuelCardReg
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/updateRefuelCardReg")
	public String updateRefuelCardReg(HttpServletRequest request,RefuelCardReg refuelCardReg)throws Exception{
		String [] fseq = request.getParameterValues("fseq");//序号
		String [] carId =request.getParameterValues("carId");//车辆Id
		String [] cfqty = request.getParameterValues("cfqty");//数量

		String [] cftrainid=request.getParameterValues("cftrainName");//教练id
		String [] cfkemu=request.getParameterValues("cfkemu");//科目
		String [] cfdepname=request.getParameterValues("cfdepname");//部门名称

		String[] cfgroupid=request.getParameterValues("cfgroupName");//教练组名称
		String [] cfteamid=request.getParameterValues("cfteamName");//教练队名称

		String[] cfoilspecid=request.getParameterValues("cfoilspecName");//汽油规格id

		String[] cfcartype=request.getParameterValues("cfcartype");//车型
		for (int i=0;i<cfqty.length;i++){
			if(cfqty[i] == null || "".equals(cfqty[i])){
				cfqty[i] ="0";
			}
		}
		String [] cfprice = request.getParameterValues("cfprice");//单价
		for (int i=0;i<cfprice.length;i++){
			if(cfprice[i] == null || "".equals(cfprice[i])){
				cfprice[i] ="0";
			}
		}
		String [] cfamount = request.getParameterValues("cfamount");//金额
		for (int i=0;i<cfamount.length;i++){
			if(cfamount[i] == null || "".equals(cfamount[i])){
				cfamount[i] ="0";
			}
		}
		String [] cfdesc =request.getParameterValues("cfdesc");//备注
		String [] cfbizdate=request.getParameterValues("cfbizdate");//车辆加油时间
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");	 
		//修改人id
	    refuelCardReg.setFlastupdateuserid(user.getFid());
	    //获取当前时间
	  	String updateTime = TimeFormat.timeFormat(new Date());
	  	refuelCardReg.setFlastupdatetime(updateTime);
	  	refuelCardReg.setFcreatorid(null);//創建人时间设置为null不让修改
	  	refuelCardReg.setFcreatetime(null);//创建时间设置为null不让修改
	  	/*if(refuelCardReg.getCfbillstate() == 5L){
	  		//审核id
	  		refuelCardReg.setFauditorid(user.getFid());
	  		refuelCardReg.setFlastupdatetime(updateTime); 
	  		//审核
	  		refuelCardRegService.updateRefuelCardReg(refuelCardReg);
	  		return "redirect:/DrivingSys/queryRefuelCardReg/look.action";
	  	}*/
	  	//修改
	  	int row = refuelCardRegService.updateRefuelCardReg(refuelCardReg, fseq, carId, cfqty, cfprice, cfamount, cfdesc,cftrainid,cfkemu,cfdepname,cfgroupid,cfteamid,cfoilspecid,cfcartype,cfbizdate);
	  	String result="";
	  	if(row >0){
			result ="1";
		}
	  	//添加日志
        customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date()) + "加油卡加油登记进行修改", null, user.getFid());
		return "redirect:/DrivingSys/queryRefuelCardReg/look.action?type="+result;
	}
	
	/**
	 * 根据fid删除加油卡加油登记
	 * @param request
	 * @param deleteId
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteRefuelCardRegByFid")
	public String deleteRefuelCardRegByFid(HttpServletRequest request, String[] deleteId,String fid)throws Exception{
		User user = (User) request.getSession().getAttribute("user");
        //删除记录
		if(fid==null || fid.equals("")){
			for (int i = 0; i < deleteId.length; i++) {
	            /*过滤为空的删除操作*/
	            if (!deleteId[i].equals("") && deleteId[i]!=null) {
	            	//根据fid查找单据编号
					RefuelCardReg refuelCardReg= refuelCardRegService.selRefuelCardRegByFid(deleteId[i]);
					//删除历史流程或者进行中的流程
					activitiUtil.deleteTask(ActivitiKey.PUBLIC_KEY,refuelCardReg.getFnumber());
	            	refuelCardRegService.deleteRefuelCardRegByFid(deleteId[i]);//删除父类
	            	refuelCardRegEntryService.deleteByParentId(deleteId[i]);
	            }
	        }	
		}else{
			//根据fid查找单据编号
			RefuelCardReg refuelCardReg= refuelCardRegService.selRefuelCardRegByFid(fid);
			//删除历史流程或者进行中的流程
			activitiUtil.deleteTask(ActivitiKey.PUBLIC_KEY,refuelCardReg.getFnumber());
			refuelCardRegService.deleteRefuelCardRegByFid(fid);
			refuelCardRegEntryService.deleteByParentId(fid);
        }
		//添加日志
        customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date()) + "加油卡加油登记进行删除", null, user.getFid());
		return "redirect:/DrivingSys/queryRefuelCardReg/look.action";
	}

	/**
	 * 提交单据
	 * @param fid
	 * @param request
	 * @param fnumber
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "submitRefuelCardRegActiviti")
	@ResponseBody
	public Object submitRefuelCardRegActiviti(String fid, HttpServletRequest request, String fnumber)throws  Exception{
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		RefuelCardReg refuelCardReg =new RefuelCardReg();
		refuelCardReg.setFid(fid);
		refuelCardReg.setCfbillstate(4L);
		refuelCardReg.setFlastupdateuserid(user.getFid());
		//创建流程
		axamine.submissionProcess(fnumber);
		int row=refuelCardRegService.updateRefuelCardReg(refuelCardReg);
		String result="failed";
		if(row >0){
			result="success";
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	/**
	 * 审核单据
	 * @param request
	 * @param fid
	 * @param agree
	 * @param auditcomment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "checkRefuelCardRegActiviti")
	@ResponseBody
	public Object checkRefuelCardRegActiviti(HttpServletRequest request,String fnumber,String fid,String agree,String auditcomment)throws  Exception{
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		RefuelCardReg refuelCardReg =new RefuelCardReg();
		//获取当前修改时间
		String updateTime = TimeFormat.timeFormat(new Date());
		String result ="failed";
		int row1=0;
		if(agree.equals("1")){//同意
			ServerResponse serverResponse = axamine.auditProcess(fnumber, agree, auditcomment);
			if(serverResponse.getStatus() == 1){//结束
				refuelCardReg.setFid(fid);
				refuelCardReg.setCfbillstate(5L);
				refuelCardReg.setFlastupdateuserid(user.getFid());
				refuelCardReg.setFauditorid(user.getFid());
				row1 = refuelCardRegService.updateRefuelCardReg(refuelCardReg);
				if(row1 >0 ){//修改单据
					result = "success";
				}
			}else if(serverResponse.getStatus() == 2){
				result = "success";
			}else{

			}
		}else{
			ServerResponse serverResponse = axamine.auditProcess(fnumber, agree, auditcomment);
			if(serverResponse.getStatus() == 2){
				refuelCardReg.setFid(fid);
				refuelCardReg.setCfbillstate(3L);
				refuelCardReg.setFlastupdateuserid(user.getFid());
				refuelCardReg.setFauditorid(user.getFid());
				//修改父类
				row1 =refuelCardRegService.updateRefuelCardReg(refuelCardReg);
				if(row1 >0){
					result = "success";
				}
			}
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	/**
	 * 反审核单据
	 * @param request
	 * @param fid
	 * @param againstAuditcomment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "againstCheckRefuelCardRegActiviti")
	@ResponseBody
	public Object againstRefuelCardRegActiviti(HttpServletRequest request,String fid,String fnumber,String againstAuditcomment )throws  Exception{
		//获取当前登录用户的信息
		User user =(User)request.getSession().getAttribute("user");
		String result ="falied";
		//将单据状态修改成保存状态3
		RefuelCardReg refuelCardReg = new RefuelCardReg();
		refuelCardReg.setFid(fid);
		refuelCardReg.setCfbillstate(3L);//保存状态
		refuelCardReg.setFauditorid(user.getFid());//设置反审计人id
		int row = refuelCardRegService.updateRefuelCardReg(refuelCardReg);
		axamine.againstAuditProcess(fnumber,againstAuditcomment);
		if (row > 0) {
			result = "success";
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}
	
	@SuppressWarnings("unchecked")
    /**
     * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
     * @return 返回PageBean实体类
     * @throws Exception
     */
    public PageBean<RefuelCardReg> getPageBean(HttpServletRequest request, String companyId, String fnumber,
            String fdescription,String carFunmber,String beginTime, String endTime) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
		psql.append(" SELECT distinct R.FCREATORID,R.FCREATETIME,R.FLASTUPDATEUSERID,R.FLASTUPDATETIME,R.FCONTROLUNITID,R.FNUMBER,to_char(R.FBIZDATE,'YYYY-MM-DD') FBIZDATE,"
					+" R.FHANDLERID,R.FDESCRIPTION,R.FHASEFFECTED,R.FAUDITORID,R.FSOURCEBILLID,R.FSOURCEFUNCTION,R.FID,"
					+" R.FFIVOUCHERED,R.CFFICOMPANYID,R.CFBILLSTATE,R.CFREFUELID,F1.fname_l2 as cfrefuelName,"
				    + " E.NAME AS checkName,U.NAME AS createName "
				    + "FROM CT_DS_REFUELCARDREG R LEFT JOIN T_E_USER U ON U.FID=R.FCREATORID LEFT JOIN T_E_USER E ON E.FID=R.FAUDITORID "
				    +" LEFT JOIN CT_DS_FILLINGCARD F1 ON F1.FID=R.CFREFUELID "
					+" LEFT JOIN CT_DS_REFUELCARDREGENTRY R1 ON R1.FPARENTID=R.FID"
				    +" LEFT JOIN CT_DS_CAR C ON C.FID = R1.CFCARID"
				    + " WHERE R.FCONTROLUNITID='" + companyId + "'");
		if (fnumber == null || fnumber.equals("")) {

		} else {
			psql.append("AND R.FNUMBER LIKE '%" + fnumber + "%' ");
		}
		if (fdescription == null || fdescription.equals("")) {

		} else {
			psql.append("AND R.FDESCRIPTION LIKE '%" + fdescription + "%'");
		}
		if (carFunmber == null || carFunmber.equals("")) {

		} else {
			psql.append("AND C.FNUMBER LIKE '%" + carFunmber + "%'");
		}
		if (beginTime == null || endTime == null) {
			/*beginTime = TimeFormat.getMonth();
		} else if (endTime == null || endTime.equals("")) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			endTime = sdf.format(new Date());
			psql.append("AND TO_CHAR(R.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'");*/
		} else {
			psql.append("AND TO_CHAR(R.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'");
		}

		psql.append(" ORDER BY to_char(R.FBIZDATE,'YYYY-MM-DD') DESC");
		//System.out.println(psql);
        int psize = 100; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = refuelCardRegService.selectPage(pindex, psql.toString(), psize);
        PageBean<RefuelCardReg> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<RefuelCardReg>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }
	
	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=refuelCardRegService.selectPageCount(psql);
		return paramMap;
	}

	/**
	 * 加油卡加油登记 导出excel
	 * @param response
	 * @param request
	 * @param fnumber
	 * @param fdescription
	 * @param carName
	 * @param beginTime
	 * @param endTime
	 */
	@RequestMapping(value = "/importRefuelCardReg")
	public void importRefuelCardReg(HttpServletResponse response, HttpServletRequest request
			, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
			, @RequestParam(value = "fdescription", defaultValue = "") String fdescription
			, @RequestParam(value = "carName", defaultValue = "") String carName
			, @RequestParam(value = "beginTime", defaultValue = "") String beginTime
			, @RequestParam(value = "endTime", defaultValue = "") String endTime){
		if("".equals(carName)){
			carName = null;
		}
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//定义接收类型
		List<Object> data = new ArrayList<>();
		//查询数据
		List<RefuelCardReg> refuelCardRegs=refuelCardRegService.selectRefuelCardReg(user.getFcompanyid(),fnumber,fdescription,beginTime,endTime);
		for (RefuelCardReg refuelCardReg :refuelCardRegs){
			refuelCardReg.setRefuelCardRegEntryList(refuelCardRegEntryService.selRefuelCardRegEntryByParentId(refuelCardReg.getFid(),carName));
			for (int i = 0; i <refuelCardReg.getRefuelCardRegEntryList().size() ; i++) {
				data.add(refuelCardReg.getFnumber());
				data.add(refuelCardReg.getFbizdate());
				data.add(refuelCardReg.getFdescription());
				data.add(refuelCardReg.getCheckName());
				data.add(refuelCardReg.getCreateName());
				if (refuelCardReg.getCfbillstate() == 3L) {
					data.add("保存");
				} else if (refuelCardReg.getCfbillstate() == 4L) {
					data.add("提交");
				} else {
					data.add("审核");
				}
				data.add(refuelCardReg.getRefuelCardRegEntryList().get(i).getCfcarName());
				data.add(refuelCardReg.getRefuelCardRegEntryList().get(i).getCfqty());
				data.add(refuelCardReg.getRefuelCardRegEntryList().get(i).getCfprice());
				data.add(refuelCardReg.getRefuelCardRegEntryList().get(i).getCfamount());
				data.add(refuelCardReg.getCfrefuelName());
				data.add(refuelCardReg.getRefuelCardRegEntryList().get(i).getCfdesc());
			}
		}
		//头部数据
		String head[] = {"单据编号", "业务日期", "参考信息", "审核人名称", "制单人名称", "单据状态", "车辆", "数量(L)", "单价", "金额", "加油卡","备注"};
		//长度
		Integer length[] = {9000, 5000, 5000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000,5000};
		try {
			//导出Excel
			CommonExport.importExcel(response, "加油卡加油登记" + TimeFormat.getNowTime2() + ".xls", "加油卡加油库登记", data, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
